package Java8实战._1_并行流._2_测量流性能;

import Java8实战._1_并行流.ParallelStreams;

import java.util.function.Function;

public class _2_测量流性能 {

    public static void main(String[] args) {
        System.out.println("Sequential sum done in : " +
                new _2_测量流性能().measureSumPerf(ParallelStreams::sequentialSum, 10_000_000) + " msecs"
        );

        System.out.println("Iterative sum done in : " +
                new _2_测量流性能().measureSumPerf(ParallelStreams::iterativeSum, 10_000_000) + " msecs"
        );

        System.out.println("Paralle sum done in : " +
                new _2_测量流性能().measureSumPerf(ParallelStreams::parallelSum, 10_000_000) + " msecs"
        );

        System.out.println("Ranged sum done in : " +
                new _2_测量流性能().measureSumPerf(ParallelStreams::rangedSum, 10_000_000) + " msecs"
        );

        System.out.println("ParallelRanged sum done in : " +
                new _2_测量流性能().measureSumPerf(ParallelStreams::parallelRangedSum, 10_000_000) + " msecs"
        );
    }

    public long measureSumPerf(Function<Long, Long> function, long n) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 100; i++) {
            long start = System.nanoTime();
            long sum = function.apply(n);
            long duration = (System.nanoTime() - start) / 1_000_000;
//            System.out.println("Result：" + sum);
            if (duration < fastest) {
                fastest = duration;
            }
        }
        return fastest;
    }
}


















